import 'dart:async';

import 'package:flutter/material.dart';
import 'package:fyi/dao/bind_dao.dart';
import 'package:fyi/event/event.dart';
import 'package:fyi/model/history_model.dart';
import 'package:fyi/pages/bind_page.dart';
import 'package:fyi/utils/bus_util.dart';
import 'package:fyi/utils/common_util.dart';
import 'package:fyi/utils/navigator_util.dart';
import 'package:sprintf/sprintf.dart';

class HistoryPage extends StatefulWidget {

  static final String sName = "/history";

  @override
  _HistoryPageState createState() => _HistoryPageState();
}

class _HistoryPageState extends State<HistoryPage> {

  List<HistoryModel> bindList = [];

  StreamSubscription subscription;

  @override
  void initState() {
    _handleRefresh();
    _initEvent();
    super.initState();
  }

  @override
  void dispose() {
    if(subscription != null) {
      subscription.cancel();
      subscription = null;
    }
    super.dispose();
  }

  Future<Null> _handleRefresh() async {
    /*BindDao.histories().then((values){
      if(values != null){
        setState(() {
          bindList.clear();
          bindList.addAll(values);
        });
      }
    }).catchError((err){
      CommonUtil.toast(err.toString());
    });*/
    try {
      var values = await BindDao.histories();
      if(values != null){
        setState(() {
          bindList.clear();
          bindList.addAll(values);
        });
      }
    }catch (e) {
      CommonUtil.toast(e.toString());
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
            color: Colors.white
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            _headerView(context),
            Container(
              padding: EdgeInsets.only(top: 16,bottom: 16),
              child: Text(CommonUtil.getS(context).bind_history,style: TextStyle(color: Colors.black,fontSize: 16),),
            ),
            new Divider(height: 1.0, color: Colors.grey,),
            MediaQuery.removePadding(
              removeTop: true,
              context: context,
              child: RefreshIndicator(
                child: _listView(context),
                onRefresh: _handleRefresh,
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _headerView(BuildContext context) {
    return Container(
      width: double.infinity,
      color: Color.fromARGB(255, 62, 146, 203),
      padding: EdgeInsets.only(top: 42),
      child: _wrapTap(_scanView(), (){
        NavigatorUtil.push(context, BindPage());
      }),
    );
  }
  
  Widget _scanView(){
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Image.asset("assets/images/ic_tag.png",width:180,height: 68),
          Container(
            decoration: BoxDecoration(
              color: Color.fromARGB(255, 72, 157, 209),
              borderRadius: BorderRadius.circular(14),
            ),
            margin: EdgeInsets.only(top: 24,bottom: 36),
            padding: EdgeInsets.fromLTRB(42, 16, 42, 16),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Image.asset("assets/images/ic_qr.png",width: 100,height: 100,),
                Container(
                  margin: EdgeInsets.only(left: 18),
                  child: Text(CommonUtil.getS(context).bind,style: TextStyle(color: Colors.white,fontSize: 18,decoration: TextDecoration.none),),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _listView(BuildContext context) {
    return ListView.builder(
        itemCount: bindList.length,
        shrinkWrap: true,
        itemBuilder: (BuildContext context, int index){
          return _item(context,bindList[index]);
        });
  }
  
  Widget _item(BuildContext context,HistoryModel model){
    return Container(
      padding: EdgeInsets.fromLTRB(16, 14, 16, 14),
      decoration: BoxDecoration(
          border: Border(bottom: BorderSide(width: 0.5, color: Colors.grey))
      ),
      child: Row(
        children: <Widget>[
          Expanded(child: Text(model.licensePlate)),
          _wrapTap(_unbindView(), (){
            CommonUtil.showAlertDialog(context, CommonUtil.getS(context).tips, sprintf(CommonUtil.getS(context).you_are_sure_unbind,[model.licensePlate]),CommonUtil.getS(context).sure , (){
              if(model?.id != null){
                BindDao.unbind(model?.id?.toString()).then((value){
                  print('value : ${value}');
                  if(value){
                    _handleRefresh();
                  }
                }).catchError((err){
                  print('err : ${err}');
                });
              }
            }, CommonUtil.getS(context).cancel, (){});
          })
        ],
      ),
    );
  }
  
  _unbindView(){
    return Container(
      child: Text(CommonUtil.getS(context).unbind,style: TextStyle(color: Color.fromARGB(255, 54, 121, 181),fontSize: 16),),
    );
  }

  _wrapTap(Container container, void Function() click) {
    return GestureDetector(
      child: container,
      onTap: (){
        if(click != null){
          click();
        }
      },
    );
  }

  void _initEvent() {
    subscription = BusUtil.eventBus.on<RefreshHistoryEvent>().listen((event){
      _handleRefresh();
    });

  }
  
}
